package mrms.api.web.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lenchu
 * @date 2019/01/31
 */
@Component
public class JwtUtils {
   public final Base64 base64 = new Base64();
   public final ObjectMapper mapper = new ObjectMapper();

   @Value("${app.security.jwt.secretKey:it is a secret}")
   public String secretKey;

   public String writeUserIdIntoJwt(String uid, String password) {
       Map<String, Object> map = new HashMap<>(1);
       map.put("id", uid);
       String s = Jwts.builder()
               .setClaims(map)
               .signWith(SignatureAlgorithm.HS256, base64.encodeToString((secretKey + password).getBytes()))
               .compact();
       return s;
   }

   public String getUserIdByJwtString(String jwt) {
       return decodeJwt(jwt).get("id");
   }

   public boolean verifyJwt(String jwt, String password) {
       try {
           Jwts.parser()
                   .setSigningKey(base64.encodeToString((secretKey + password).getBytes()))
                   .parse(jwt);
       } catch (Exception e) {
           return false;
       }
       return true;
   }

   public Map<String, String> decodeJwt(String jwt) {
       try {
           String[] jwtArray = jwt.split("\\.");
           byte[] decode = base64.decode(jwtArray[1]);
           String d = new String(decode);
           Map map = mapper.readValue(d, Map.class);
           return map;
       } catch (IOException e) {
           throw new RuntimeException("身份验证失败", e);
       }
   }
}
